#include "gui.h"

#include <wx/wx.h>
#include <wx/grid.h>
#include <wx/button.h>
#include <wx/sizer.h>
#include <wx/stattext.h>

#include "db.h"
#include "db_op.h"
#include "db_info.h"
#include "lib_manager.h"
#include "config.h"
#include "book_info.h"
#include "time.h"
#include "lib_init.h"

#include "Dialogs/AddBookDialog.h"
#include "Dialogs/AddPurchaseDialog.h"
#include "Dialogs/AddDiscardDialog.h"
#include "Dialogs/AddBorrowDialog.h"
#include "Dialogs/ReturnBookDialog.h"



BookManagerFrame::BookManagerFrame(const wxString& title)
    : wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(800, 600)) {
    // 创建菜单
    wxMenu* fileMenu = new wxMenu;
    fileMenu->Append(5001, wxT("重新连接数据库"),
                     wxT("重新连接数据库"));
    fileMenu->Append(5002, wxT("初始化表"),
                     wxT("初始化表"));


    // 创建菜单栏                 
    wxMenuBar* menuBar = new wxMenuBar();
    menuBar->Append(fileMenu, wxT("&选项"));
    SetMenuBar(menuBar);

    // 创建一个wxStaticText控件，并设置其初始文本
    staticText = new wxStaticText(this, wxID_ANY, wxT("表格!"),
                                                wxDefaultPosition, wxDefaultSize,
                                                wxALIGN_LEFT); // 文本居中对齐


    // 创建按钮
    wxButton* putBookinfoButton = new wxButton(this, wxID_ANY, wxT("增加图书信息"));
    wxButton* PurchaseBookButton = new wxButton(this, wxID_ANY, wxT("采购图书"));
    wxButton* removeBookButton = new wxButton(this, wxID_ANY, wxT("淘汰图书"));
    wxButton* borrowBookButton = new wxButton(this, wxID_ANY, wxT("租借图书"));
    wxButton* returnBookButton = new wxButton(this, wxID_ANY, wxT("归还图书"));
    wxButton* queryBooksButton = new wxButton(this, wxID_ANY, wxT("查询图书"));
    wxButton* queryPurchasesButton = new wxButton(this, wxID_ANY, wxT("查询采购"));
    wxButton* queryRemovalsButton = new wxButton(this, wxID_ANY, wxT("查询淘汰"));
    wxButton* queryBorrowingsButton = new wxButton(this, wxID_ANY, wxT("查询租借"));
    wxButton* statisticsButton = new wxButton(this, wxID_ANY, wxT("统计"));

    // 


    // 创建网格控件
    m_Grid = new wxGrid(this, wxID_ANY);


    //----------------------------------------------------------------




     // 绑定事件
    Bind(wxEVT_BUTTON, &BookManagerFrame::OnputBookinfo, this, putBookinfoButton->GetId());
    Bind(wxEVT_BUTTON, &BookManagerFrame::OnPurchaseBook, this, PurchaseBookButton->GetId());
    Bind(wxEVT_BUTTON, &BookManagerFrame::OnRemoveBook, this, removeBookButton->GetId());
    Bind(wxEVT_BUTTON, &BookManagerFrame::OnBorrowBook, this, borrowBookButton->GetId());
    Bind(wxEVT_BUTTON, &BookManagerFrame::OnReturnBook, this, returnBookButton->GetId());
    Bind(wxEVT_BUTTON, &BookManagerFrame::OnQueryBooks, this, queryBooksButton->GetId());
    Bind(wxEVT_BUTTON, &BookManagerFrame::OnQueryPurchases, this, queryPurchasesButton->GetId());
    Bind(wxEVT_BUTTON, &BookManagerFrame::OnQueryRemovals, this, queryRemovalsButton->GetId());
    Bind(wxEVT_BUTTON, &BookManagerFrame::OnQueryBorrowings, this, queryBorrowingsButton->GetId());
    Bind(wxEVT_BUTTON, &BookManagerFrame::OnStatistics, this, statisticsButton->GetId());

    Bind(wxEVT_MENU, &BookManagerFrame::Correct_Database, this, 5001);
    Bind(wxEVT_MENU, &BookManagerFrame::Initialization_Table, this, 5002);

    // 将 wxEVT_SIZE 事件绑定到 OnSize 方法
    Bind(wxEVT_SIZE, &BookManagerFrame::OnSize, this);


    // 初始化网格
    m_Grid->CreateGrid(10, 5);
    m_Grid->AutoSizeColumns();
    m_Grid->EnableEditing(false);

    // 创建布局管理器
    wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL);
    wxBoxSizer* buttonSizer = new wxBoxSizer(wxHORIZONTAL);

    // 添加按钮到布局管理器
    buttonSizer->Add(putBookinfoButton, 0, wxALL | wxEXPAND, 1);
    buttonSizer->Add(PurchaseBookButton, 0, wxALL | wxEXPAND, 1);
    buttonSizer->Add(removeBookButton, 0, wxALL | wxEXPAND, 1);
    buttonSizer->Add(borrowBookButton, 0, wxALL | wxEXPAND, 1);
    buttonSizer->Add(returnBookButton, 0, wxALL | wxEXPAND, 1);
    buttonSizer->Add(queryBooksButton, 0, wxALL | wxEXPAND, 1);
    buttonSizer->Add(queryPurchasesButton, 0, wxALL | wxEXPAND, 1);
    buttonSizer->Add(queryRemovalsButton, 0, wxALL | wxEXPAND, 1);
    buttonSizer->Add(queryBorrowingsButton, 0, wxALL | wxEXPAND, 1);
    buttonSizer->Add(statisticsButton, 0, wxALL | wxEXPAND, 1);

    // 添加网格和按钮布局到主布局管理器
    mainSizer->Add(buttonSizer, 0, wxEXPAND | wxALL, 1);
    mainSizer->Add(staticText, 0, wxEXPAND | wxALL, 1);
    mainSizer->Add(m_Grid, 1, wxEXPAND | wxALL, 0);


    SetSizer(mainSizer);
    // 确保sizer中的所有子项都按照新的窗口大小进行布局
    Layout();

    // 绑定窗口大小改变事件到一个处理函数，以便动态调整
    Bind(wxEVT_SIZE, &BookManagerFrame::OnSize, this);

    // 读取数据库登录账户信息
    DatabaseInfo* db_info;
    db = new Library_Database();
    auto value = read_database_info();
    if (!value.has_value()) {
#ifdef DEBUG_PRINTS
        std::cerr << "XML parsing failed!" << std::endl;
#endif
        wxMessageBox("XML 文件解析失败", "失败", wxICON_ERROR | wxOK);
    }
    // 连接数据库
    else {
        db_info = *value;
        if (!db->connect(db_info)) {
            wxMessageBox("数据库连接失败", "失败", wxICON_ERROR | wxOK);
        }
        delete db_info;


        // 初始化时调用 OnQueryBooks 函数
        wxCommandEvent dummyEvent;
        OnQueryBooks(dummyEvent);
    }


}

BookManagerFrame::~BookManagerFrame() {
    // 释放资源
    delete db;
}


void BookManagerFrame::Correct_Database(wxCommandEvent& event) {
    delete db;

    // 读取数据库登录账户信息
    db = new Library_Database();
    auto value = read_database_info();
    if (!value.has_value()) {
#ifdef DEBUG_PRINTS
        std::cerr << "XML parsing failed!" << std::endl;
#endif
        wxMessageBox("XML 文件解析失败", "失败", wxICON_ERROR | wxOK);
    }
    // 连接数据库
    else {
        DatabaseInfo* db_info;
        db_info = *value;

        if (!db->connect(db_info)) {
            wxMessageBox("数据库连接失败", "失败", wxICON_ERROR | wxOK);
        }
        else {
            wxMessageBox("数据库连接成功", "成功", wxICON_INFORMATION | wxOK);
        }
        delete db_info;
    }

}


void BookManagerFrame::Initialization_Table(wxCommandEvent& event) {
    LibraryTableCreator t = LibraryTableCreator(db);
    if (t.LibarayTableInit()) {
        wxMessageBox("表格初始化成功", "成功", wxICON_INFORMATION | wxOK);
    }
    else {
        wxMessageBox("表格初始化失败", "失败", wxICON_ERROR | wxOK);
    }
}




void BookManagerFrame::UpdateGridWithQueryResult(const QueryResult& result, const std::vector<std::string>& headers) {
    // 清理网格
    m_Grid->ClearGrid();
    if (m_Grid->GetNumberCols() > 0) {
        m_Grid->DeleteCols(0, m_Grid->GetNumberCols());
    }
    if (m_Grid->GetNumberRows() > 0) {
        m_Grid->DeleteRows(0, m_Grid->GetNumberRows());
    }

    // 设置表头
    m_Grid->AppendCols(headers.size());
    for (size_t i = 0; i < headers.size(); ++i) {
        m_Grid->SetColLabelValue(i, wxString::FromUTF8(headers[i].c_str()));
    }

    // 填充数据
    size_t rowCount = result.rows.size();
    if (rowCount > 0) {
        m_Grid->AppendRows(rowCount);

        for (size_t row = 0; row < rowCount; ++row) {
            const RowData& rowData = result.rows[row];
            for (size_t col = 0; col < rowData.fields.size(); ++col) {
                m_Grid->SetCellValue(row, col, wxString::FromUTF8(rowData.fields[col].c_str()));
            }
        }
    }

    // 自动调整列宽
    m_Grid->AutoSizeColumns();

    // 刷新界面
    Refresh();
}

void BookManagerFrame::OnputBookinfo(wxCommandEvent& event) {
    // 创建更新管理器
    Library_UpdateManager updateManager(db);

    // 显示添加图书对话框
    AddBookDialog dlg(this);
    if (dlg.ShowModal() == wxID_OK) {
        // 获取用户输入的图书信息
        BookInfo bookInfo = dlg.GetBookInfo();

        // 添加图书信息到数据库
        if (updateManager.AddBookInfo(bookInfo)) {
            wxMessageBox("图书信息添加成功", "成功", wxICON_INFORMATION | wxOK);
            wxCommandEvent dummyEvent;
            OnQueryBooks(dummyEvent);
        }
        else {
            wxMessageBox("添加图书信息失败，请检查输入", "错误", wxICON_ERROR | wxOK);
        }
    }
}

void BookManagerFrame::OnPurchaseBook(wxCommandEvent& event) {
    // 调用后端添加采购图书信息的方法

    // 创建更新管理器
    Library_UpdateManager updateManager(db);

    // 显示添加采购信息对话框
    AddPurchaseDialog dlg(this);
    if (dlg.ShowModal() == wxID_OK) {
        // 获取用户输入的采购信息
        PurchaseInfo purchaseInfo = dlg.GetPurchaseInfo();

        // 添加采购信息到数据库
        if (updateManager.BookPurchase(purchaseInfo)) {
            wxMessageBox("图书采购信息添加成功", "成功", wxICON_INFORMATION | wxOK);
            wxCommandEvent dummyEvent;
            OnQueryPurchases(dummyEvent);
        }
        else {
            wxMessageBox("添加图书采购信息失败，请检查输入", "错误", wxICON_ERROR | wxOK);
        }
    }

}

void BookManagerFrame::OnRemoveBook(wxCommandEvent& event) {
    // 调用后端淘汰图书的方法

    // 创建更新管理器
    Library_UpdateManager updateManager(db);

    // 显示添加淘汰信息对话框
    AddDiscardDialog dlg(this);
    if (dlg.ShowModal() == wxID_OK) {
        // 获取用户输入的淘汰信息
        DiscardInfo discardInfo = dlg.GetDiscardInfo();

        // 添加淘汰信息到数据库
        if (updateManager.BookElimination(discardInfo)) {
            wxCommandEvent dummyEvent;
            OnQueryRemovals(dummyEvent);
            wxMessageBox("图书淘汰信息添加成功", "成功", wxICON_INFORMATION | wxOK);
        }
        else {
            wxMessageBox("添加图书淘汰信息失败，请检查输入", "错误", wxICON_ERROR | wxOK);
        }
    }


}

void BookManagerFrame::OnBorrowBook(wxCommandEvent& event) {
    // 调用后端借阅图书的方法

    // 创建更新管理器
    Library_UpdateManager updateManager(db);

    // 显示添加借阅信息对话框
    AddBorrowDialog dlg(this);
    if (dlg.ShowModal() == wxID_OK) {
        // 获取用户输入的借阅信息
        BorrowInfo borrowInfo = dlg.GetBorrowInfo();

        // 添加借阅信息到数据库
        if (updateManager.BookRent(borrowInfo)) {
            wxCommandEvent dummyEvent;
            OnQueryBorrowings(dummyEvent);
            wxMessageBox("图书借阅信息添加成功", "成功", wxICON_INFORMATION | wxOK);
        }
        else {
            wxMessageBox("添加图书借阅信息失败", "错误", wxICON_ERROR | wxOK);
        }
    }

}

void BookManagerFrame::OnReturnBook(wxCommandEvent& event) {
    // 调用后端归还图书的方法

    // 创建更新管理器
    Library_UpdateManager updateManager(db);

    // 显示添加归还信息对话框
    ReturnBookDialog dlg(this);
    if (dlg.ShowModal() == wxID_OK) {
        // 获取用户输入的归还信息
        auto [borrowId, returnDate] = dlg.GetReturnInfo();

        // 更新图书归还信息到数据库
        if (updateManager.BookReturn(borrowId, returnDate)) {
            wxCommandEvent dummyEvent;
            OnQueryBorrowings(dummyEvent);
            wxMessageBox("图书归还成功", "成功", wxICON_INFORMATION | wxOK);
        }
        else {
            wxMessageBox("图书归还失败，请检查输入", "错误", wxICON_ERROR | wxOK);
        }
    }

}

void BookManagerFrame::OnQueryBooks(wxCommandEvent& event) {
    staticText->SetLabel(wxT("图书信息"));

    // 查询所有图书信息并更新表格
    Library_QueryManager qm(db);
    QueryResult result = qm.GetBooksInfo();
    std::vector<std::string> headers = { "图书ID", "图书标题", "作者", "出版社", "出版时间", "库存" };

    UpdateGridWithQueryResult(result, headers);
    wxSizeEvent dummyEvent(this->GetSize());
    OnSize(dummyEvent);
}



void BookManagerFrame::OnQueryPurchases(wxCommandEvent& event) {
    staticText->SetLabel(wxT("采购记录"));


    // 查询所有采购记录并更新表格
    Library_QueryManager qm(db);
    QueryResult result = qm.GetPurchasesInfo();
    std::vector<std::string> headers = { "采购ID", "图书ID", "采购数量", "采购日期", "采购价格" };

    UpdateGridWithQueryResult(result, headers);
    wxSizeEvent dummyEvent(this->GetSize());
    OnSize(dummyEvent);
}

void BookManagerFrame::OnQueryRemovals(wxCommandEvent& event) {
    staticText->SetLabel(wxT("淘汰记录"));


    // 查询所有淘汰记录并更新表格
    Library_QueryManager qm(db);
    QueryResult result = qm.GetDiscardsInfo();
    std::vector<std::string> headers = { "淘汰ID", "图书ID", "淘汰数量", "淘汰日期" };
    UpdateGridWithQueryResult(result, headers);
    wxSizeEvent dummyEvent(this->GetSize());
    OnSize(dummyEvent);
}

void BookManagerFrame::OnQueryBorrowings(wxCommandEvent& event) {
    staticText->SetLabel(wxT("借阅记录"));

    // 查询所有借阅记录并更新表格
    Library_QueryManager qm(db);
    QueryResult result = qm.GetBorrowsInfo();
    std::vector<std::string> headers = { "借阅ID", "图书ID", "用户ID", "借阅日期","返还日期","借阅状态" };
    UpdateGridWithQueryResult(result, headers);
    wxSizeEvent dummyEvent(this->GetSize());
    OnSize(dummyEvent);
}


void BookManagerFrame::OnStatistics(wxCommandEvent& event) {
    // 执行统计并将结果展示给用户

    Library_StatisticsManager statsManager(db);

    // 获取所有统计信息
    QueryResult t1 = statsManager.GetInventoryStatistics();
    QueryResult t2 = statsManager.GetBorrowsStatistics();
    QueryResult t3 = statsManager.GetPurchasesStatistics();
    QueryResult t4 = statsManager.GetDiscardsStatistics();
    if (t1.rows.size() == 0 || t2.rows.size() == 0 || t3.rows.size() == 0 || t4.rows.size() == 0) {
        return;
    }

    // 格式化统计结果为字符串
    wxString statsResult;


    // 添加各个统计结果到总的字符串中
    statsResult += wxT("库存情况统计:\n");
    statsResult += wxT("总图书数量:");
    statsResult += t1.rows[0].fields[0];
    statsResult += "\n";

    statsResult += wxT("租借情况统计:\n");
    statsResult += wxT("总租借数量:");
    statsResult += t2.rows[0].fields[0];
    statsResult += wxT("已借出数量:");
    statsResult += t2.rows[0].fields[1];
    statsResult += wxT("已归还数量:");
    statsResult += t2.rows[0].fields[2];
    statsResult += wxT("逾期未还数量:");
    statsResult += t2.rows[0].fields[3];
    statsResult += "\n";

    statsResult += wxT("采购情况统计:\n");
    statsResult += wxT("采购记录数量:");
    statsResult += t3.rows[0].fields[0];
    statsResult += wxT("总采购数量:");
    statsResult += t3.rows[0].fields[1];
    statsResult += wxT("最晚采购日期:");
    statsResult += t3.rows[0].fields[2];
    statsResult += "\n";

    statsResult += wxT("淘汰情况统计:\n");
    statsResult += wxT("淘汰记录数量:");
    statsResult += t4.rows[0].fields[0];
    statsResult += wxT("总淘汰数量:");
    statsResult += t4.rows[0].fields[1];
    statsResult += wxT("最晚淘汰日期:");
    statsResult += t4.rows[0].fields[2];
    statsResult += "\n";












    // 使用对话框显示统计结果
    wxMessageDialog dlg(this, statsResult, wxT("统计信息"), wxOK | wxICON_INFORMATION);
    dlg.ShowModal();

}


void BookManagerFrame::OnSize(wxSizeEvent& event) {
    // 确保网格已经创建
    if (m_Grid) {
        // 获取网格的客户端矩形
        wxRect rect = m_Grid->GetClientRect();
        int totalWidth = rect.width - 60;

        // 如果有垂直滚动条，需要预留空间
        if (m_Grid->GetScrollRange(wxVERTICAL) > m_Grid->GetScrollPos(wxVERTICAL))
            totalWidth -= wxSystemSettings::GetMetric(wxSYS_VSCROLL_X);

        // 获取列的数量
        int numCols = m_Grid->GetNumberCols();

        // 计算每列的新宽度
        int colWidth = totalWidth / numCols;

        // 设置每列的宽度
        for (int i = 0; i < numCols; ++i) {
            m_Grid->SetColSize(i, colWidth);
        }
    }

    event.Skip(); // 确保默认处理也发生
    Refresh();
}